#include "index.hpp"
#include "jsoncpp/json/json.h"
#include <algorithm>
#include "log.hpp"
using namespace ns_index;
namespace ns_searcher
{
    class Searcher
    {
    private:
        ns_index::Index *index;

    public:
        Searcher() {}
        ~Searcher() {}

    public:
        void InitSearcher(const string &input)
        {
            // 1.获取或创建index对象
            index = ns_index::Index::GetInstance();
            // cout << "获取index单例成功" << endl;
            LOG(NORMAL, "获取index单例成功");
            // 2.根据index对象创建索引
            index->BuildIndex(input);
            // cout << "建立所有索引完毕!" << endl;
            LOG(NORMAL, "建立所有索引完毕!");
        }
        void Search(const string &query, string *json_string)
        {
            // 1.分词，对quary按照searcher的要求进行分词
            vector<string> words;
            ns_util::JiebaUtil::CutString(query, words);
            // 2.触发，根据分词的各个词进行index查找
            vector<InvertedElemPrint> inverted_list_all;
            std::unordered_map<int, InvertedElemPrint> tokens_map;
            for (auto &word : words)
            {
                ns_index::InvertedList *inverted_list = index->GetInvertedList(word); // vector<invertedElem>
                if (inverted_list == nullptr)
                    continue;
                for (auto &elem : *inverted_list) // 去重处理
                {
                    auto &item = tokens_map[elem.doc_id];
                    item.doc_id = elem.doc_id;
                    item.weight += elem.weight;
                    item.words.push_back(std::move(elem.word));
                }
                // inverted_list_all.insert(inverted_list_all.end(), inverted_list->begin(), inverted_list->end());
            }
            for (const auto &item : tokens_map)
                inverted_list_all.push_back(std::move(item.second));
            // 3.合并排序，汇总查找结果，按照weight降序排序
            std::sort(inverted_list_all.begin(), inverted_list_all.end(),
                      [](const ns_index::InvertedElemPrint &e1, const ns_index::InvertedElemPrint &e2)
                      {
                          return e1.weight > e2.weight;
                      });
            // std::sort(inverted_list_all.begin(), inverted_list_all.end(),
            //           [](const ns_index::InvertedElem &e1, const ns_index::InvertedElem &e2)
            //           {
            //               return e1.weight > e2.weight;
            //           });
            // 4.构建，根据查找出来的结果构建json串--jsoncpp
            Json::Value root;
            for (auto &item : inverted_list_all)
            {
                ns_index::DocInfo *doc = index->GetForwardIndex(item.doc_id);
                Json::Value elem;
                elem["title"] = doc->title;
                elem["desc"] = GetDesc(doc->content, item.words[0]);
                elem["url"] = doc->url;
                // for test
                //  elem["doc_id"] = item.doc_id;
                //  elem["weight"] = item.weight;
                root.append(elem);
            }

            Json::StyledWriter writer;
            *json_string = writer.write(root);
        }

        string GetDesc(const string &html_content, string &word) // 根据文本内容和关键字获取摘要
        {
            int prev_step = 50;
            int next_step = 100;
            // 1.查找字符串(忽略大小写)
            //  size_t pos = html_content.find(word);
            //  if (pos == string::npos)
            //      return "can't find word";
            auto iter = std::search(html_content.begin(), html_content.end(), word.begin(), word.end(),
                                    [](int x, int y)
                                    { return (std::tolower(x) == std::tolower(y)); });
            if (iter == html_content.end())
                return "can't find word";

            // 2.检查位置
            int pos = std::distance(html_content.begin(), iter);
            int start = 0;
            int end = html_content.size() - 1;
            if ((int)pos - prev_step > start)
                start = pos - prev_step;
            if (pos + next_step < end)
                end = pos + next_step;

            if (start > end)
                return "start>end";

            string ret;
            if (start != 0)
                ret += ". . . ";
            ret += html_content.substr(start, end - start + 1);
            if (end != html_content.size() - 1)
                ret += " . . . . . .";
            return ret;
        }
    };
}